//
//  NewsViewController.m
//  GentlemanAnime
//
//  Created by dlios on 15-6-29.
//  Copyright (c) 2015年 lanou3g.com 蓝欧科技. All rights reserved.
//

#import "NewsViewController.h"
#import "AFNetworking.h"
#import "AFNetworkReachabilityManager.h"
#import "NewsTableViewModel.h"
#import "UIImageView+WebCache.h"
#import "NewsDetailViewController.h"
#import "NewsTableViewCell.h"
#import "SearchViewController.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "FireView.h"


#import "DownloadSingletonTool.h"
@interface NewsViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)NSMutableArray *AnimeArr;
@property(nonatomic,retain)UITableView *tableView;
@property(nonatomic,assign) NSInteger count;
@property(nonatomic, retain)MBProgressHUD *HUD;

// 小火箭
@property(nonatomic, retain)UIButton *topButton;
@property(nonatomic, retain)FireView *fire;

@end

@implementation NewsViewController

- (void)dealloc
{
    [_fire release];
    [_HUD release];
    [_tableView release];
    [_AnimeArr release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
         self.count = 2;
        self.AnimeArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    
    UILabel *titlelebel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    titlelebel.text = @"漫资讯";
    titlelebel.font = [UIFont boldSystemFontOfSize:18];
    titlelebel.textAlignment = NSTextAlignmentCenter;
    titlelebel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titlelebel;
    [titlelebel release];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = self.tableView.frame.size.height / 5;
    [_tableView release];
    
//    //漫资讯首页的搜索按钮
//    UIButton *SearchButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    SearchButton.frame = CGRectMake(0, 0, 30, 30);
//    [SearchButton setImage:[UIImage imageNamed:@"搜索"] forState:UIControlStateNormal];
//    [SearchButton addTarget:self action:@selector(SearchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:SearchButton];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    [leftButton setImage:[UIImage imageNamed:@"用户1"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];

    
    
    // 小菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //样式
    self.HUD.mode = MBProgressHUDModeIndeterminate;
    //颜色
    self.HUD.color = [UIColor colorWithRed:0.334 green:0.619 blue:1.000 alpha:1.000];
    
 //上拉刷新,下拉加载的方法
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self createData];
   
}


#pragma mark 置顶按钮点击方法
- (void)topButtonClick:(UIButton *)button {
    CGRect oldRect = self.topButton.frame;
    [UIView animateWithDuration:0.8 animations:^{
        self.fire.alpha = 1;
    } completion:^(BOOL finished) {
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
        [UIView animateWithDuration:1 animations:^{
            self.topButton.frame = CGRectMake(oldRect.origin.x, oldRect.origin.y - 200, oldRect.size.width, oldRect.size.height);
            self.topButton.alpha = 0;
            self.fire.alpha = 0;
        } completion:^(BOOL finished) {
            self.topButton.frame = oldRect;
            [UIView animateWithDuration:0.1 animations:^{
                self.topButton.alpha = 1;
            }];
        }];
    }];
}

//上拉刷新
-(void)headerRereshing {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://manmi.me?c=info&m=news&page=1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.AnimeArr removeAllObjects];
        NSDictionary *dic = responseObject;
        NSArray *arr = dic[@"list"];
        for (NSDictionary *tempDic in arr) {

    NewsTableViewModel *TableViewModel = [[NewsTableViewModel alloc]init];
    [TableViewModel setValuesForKeysWithDictionary:tempDic];
            [self.AnimeArr addObject:TableViewModel];
            [TableViewModel release];
        }
        [self.tableView reloadData];
        self.count = 2;
        [self.tableView headerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}
//下拉加载
-(void)footerRereshing {

    NSString *url = [NSString stringWithFormat:@"http://manmi.me?c=info&m=news&page=%ld",(long)self.count];
       AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *arr = dic[@"list"];
        for (NSDictionary *tempDic in arr) {
            NewsTableViewModel *TableViewModel = [[NewsTableViewModel alloc]init];
            [TableViewModel setValuesForKeysWithDictionary:tempDic];
            if ([TableViewModel.release rangeOfString:@"admin"].location == NSNotFound) {
                [self.AnimeArr addObject:TableViewModel];
            }
            [TableViewModel release];
        }
        [self.tableView reloadData];
        self.count++;
        [self.tableView footerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}

-(void)createData
{
//通过AFN进行网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://manmi.me?c=info&m=news&page=1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *arr = dic[@"list"];
        for (NSDictionary *tempDic in arr) {
            NewsTableViewModel *TableViewModel = [[NewsTableViewModel alloc]init];
            [TableViewModel setValuesForKeysWithDictionary:tempDic];
            if ([TableViewModel.release rangeOfString:@"admin"].location == NSNotFound) {
                [self.AnimeArr addObject:TableViewModel];
            }
            [TableViewModel release];
        }
        [self.tableView reloadData];
        //置顶按钮
        [self createTopButton];
        //小菊花
        [self.HUD hide:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];

}

- (void)createTopButton {
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 60, self.view.frame.size.height - 106, 40, 40)];
    backView.backgroundColor = [UIColor colorWithRed:0.230 green:0.692 blue:0.901 alpha:0.800];
    backView.layer.cornerRadius = 20;
    [self.view addSubview:backView];
    [backView release];
    
    UIView *midView = [[UIView alloc] initWithFrame:CGRectMake(1, 1, 38, 38)];
    midView.layer.cornerRadius = 18;
    midView.layer.borderWidth = 1.5f;
    midView.layer.borderColor = [[UIColor colorWithRed:0.965 green:0.980 blue:0.992 alpha:1.000] CGColor];
    [backView addSubview:midView];
    [midView release];
    
    // 置顶按钮
    self.topButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.topButton.frame = CGRectMake(6, 6, 28, 28);
    [backView addSubview:self.topButton];
    [self.topButton setTintColor:[UIColor whiteColor]];
    [self.topButton setImage:[UIImage imageNamed:@"iconfont-top(2)"] forState:UIControlStateNormal];
    [self.topButton addTarget:self action:@selector(topButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.fire = [[FireView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
    self.fire.center = CGPointMake(14, 35);
    self.fire.alpha = 0;
    [self.topButton addSubview:self.fire];
    [_fire release];
    self.fire.transform = CGAffineTransformRotate(self.fire.transform, M_PI);
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.AnimeArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[NewsTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse]autorelease];
    }
    
    NewsTableViewModel *TableViewModel = self.AnimeArr[indexPath.row];
    [cell.AnimeImageView sd_setImageWithURL:[NSURL URLWithString:TableViewModel.image] placeholderImage:[UIImage imageNamed:@"新闻占位图"]];
    cell.TitleLabel.text = TableViewModel.title;
    cell.TimeLabel.text = TableViewModel.time;
    cell.BrowseLabel.text = TableViewModel.browse;
    cell.ReleaseLabel.text = TableViewModel.release;
    cell.DescribeLabel.text = TableViewModel.describe;
    
    return cell;
}

//跳转到详情页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsDetailViewController *detailVC = [[NewsDetailViewController alloc]init];
    
    NewsTableViewModel *TableViewModel = self.AnimeArr[indexPath.row];
    detailVC.newsID = TableViewModel.Id;
    detailVC.newsModel = self.AnimeArr[indexPath.row];
    [self.navigationController pushViewController:detailVC animated:YES];
    
    [detailVC release];
}

- (void)rightClick:(UIButton *)button
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

#pragma mark 两个button的点击方法
- (void)leftClick:(UIButton *)button
{
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC openLeftView];
}

////搜索的SerachButton跳转(漫资讯的搜索按钮的跳转方式)
//- (void)SearchButtonClick:(UIButton *)button
//{
//    SearchViewController *SearchAnime = [[SearchViewController alloc]init];
//    [self.navigationController pushViewController:SearchAnime animated:YES];
//    [SearchAnime release];
//    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
